const express = require('express')
const app = express()
// 解析token中间件
const expressJwt = require('express-jwt')
const { jwtSecretKey } = require('./config/jwtSecretKey');

// 解析post请求的body数据
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// 配置跨域请求
const cors = require('cors')
app.use(cors())

// expressJwt({secret:jwtSecretKey})解析token的中间件
// unless({path:[/^\/user\//]})指定哪些接口不需要访问权限
app.use(expressJwt({ secret: jwtSecretKey, algorithms: ['HS256'] }).unless({ path: ['/user/register', '/user/login', '/book/find', '/book/update', '/book/delete', '/book/add', '/book/bookData'] }))

// 用户路由模块
const userRouter = require('./router/user');
app.use('/user', userRouter);

// 图书路由模块
const bookRouter = require('./router/book');
app.use('/book', bookRouter);

// joi校验表单数据并提示错误信息
const joi = require('joi');
// 错误级别中间件
app.use(function (err, req, res, next) {
  // joi 参数校验失败
  if (err instanceof joi.ValidationError) {
    return res.send({
      status: 1,
      message: err.message,
    });
  }
  // token校验失败
  if (err.name === 'UnauthorizedError') {
    return res.send({ status: 1, message: '身份认证失败' })
  }
  // 未知错误
  res.send({
    status: 1,
    message: err.message,
  });
});

app.listen(3000, () => {
  console.log('服务启动在http://127.0.0.1:3000')
})